<template>
  <base-table-layout
    title="订单管理"
    :total="total"
    :current-page="currentPage"
    :page-size="pageSize"
    @update:currentPage="val => currentPage = val"
    @update:pageSize="val => pageSize = val"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  >
    <!-- 搜索区域 -->
    <template #search>
      <el-input
        v-model="searchForm.orderId"
        placeholder="订单号"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleSearch"
      />
      <el-select v-model="searchForm.supplierId" placeholder="供应商名称" clearable style="width: 200px;" class="filter-item">
        <el-option
          v-for="item in supplierOptions"
          :key="item.supplierId"
          :label="item.supplierName"
          :value="item.supplierId"
        />
      </el-select>
      <el-select v-model="searchForm.materialId" placeholder="物资名称" clearable style="width: 200px;" class="filter-item">
        <el-option
          v-for="item in materialOptions"
          :key="item.materialId"
          :label="item.materialName"
          :value="item.materialId"
        />
      </el-select>
      <el-select v-model="searchForm.orderStatus" placeholder="订单状态" clearable style="width: 200px;" class="filter-item">
        <el-option
          v-for="(label, value) in statusOptions"
          :key="value"
          :label="label"
          :value="Number(value)"
        />
      </el-select>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleSearch"
      >搜索</el-button>
      <el-button
        class="filter-item"
        type="info"
        icon="el-icon-refresh"
        @click="resetSearch"
      >重置</el-button>
    </template>

    <!-- 操作区域 -->
    <template #operation>
      <el-button
        type="success"
        icon="el-icon-plus"
        @click="handleAdd"
      >新增</el-button>
      <!-- 新增批量删除按钮 -->
      <el-button
        type="danger"
        icon="el-icon-delete"
        @click="handleBatchDelete"
      >批量删除</el-button>
    </template>

    <!-- 表格区域 -->
    <template #table>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          width="56"
        />
        <el-table-column prop="orderId" label="订单ID" />
        <el-table-column prop="supplierId" label="供应商名称" width="260">
          <template slot-scope="scope">
            {{ getSupplierName(scope.row.supplierId) }}
          </template>
        </el-table-column>
        <el-table-column prop="materialId" label="物资名称" width="240">
          <template slot-scope="scope">
            {{ getMaterialName(scope.row.materialId) }}
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="采购数量" width="140" />
        <el-table-column prop="unitPrice" label="单价" width="150" />
        <el-table-column prop="totalAmount" label="总金额" width="160" />
        <el-table-column prop="orderStatus" label="订单状态" width="116">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.orderStatus)">
              {{ getStatusText(scope.row.orderStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!-- 弹窗区域 -->
    <template #dialogs>
      <!-- 新增/编辑采购订单对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="50%">
        <el-form :model="purchaseOrderForm" :rules="rules" ref="purchaseOrderForm" label-width="100px">
          <div class="form-row">
            <el-form-item label="供应商名称" prop="supplierId">
              <el-select v-model="purchaseOrderForm.supplierId" style="width: 100%">
                <el-option
                  v-for="item in supplierOptions"
                  :key="item.supplierId"
                  :label="item.supplierName"
                  :value="item.supplierId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="物资名称" prop="materialId">
              <el-select v-model="purchaseOrderForm.materialId" style="width: 100%">
                <el-option
                  v-for="item in materialOptions"
                  :key="item.materialId"
                  :label="item.materialName"
                  :value="item.materialId"
                />
              </el-select>
            </el-form-item>
          </div>
          <div class="form-row">
            <el-form-item label="采购数量" prop="quantity">
              <el-input-number v-model="purchaseOrderForm.quantity" :min="1" style="width: 100%"></el-input-number>
            </el-form-item>
            <el-form-item label="单价" prop="unitPrice">
              <el-input-number v-model="purchaseOrderForm.unitPrice" :precision="2" :step="0.1" :min="0" style="width: 100%"></el-input-number>
            </el-form-item>
          </div>
          <div class="form-row">
            <el-form-item label="订单状态" prop="orderStatus">
              <el-select v-model="purchaseOrderForm.orderStatus" style="width: 100%">
                <el-option label="新建" :value="1"></el-option>
                <el-option label="已确认" :value="2"></el-option>
                <el-option label="已完成" :value="3"></el-option>
              </el-select>
            </el-form-item>
          </div>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </el-dialog>
    </template>
  </base-table-layout>
</template>

<script>
import request from '@/utils/request'
import _ from 'lodash'
import BaseTableLayout from '@/components/BaseTableLayout.vue'

export default {
  name: 'PurchaseOrder',
  components: {
    BaseTableLayout
  },
  data() {
    return {
      loading: false,
      searchForm: {
        orderId: '',
        supplierId: '',
        materialId: '',
        orderStatus: ''
      },
      supplierOptions: [],
      materialOptions: [],
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      dialogTitle: '',
      purchaseOrderForm: {
        supplierId: '',
        materialId: '',
        quantity: 1,
        unitPrice: 0,
        totalAmount: 0,
        orderStatus: 1
      },
      rules: {
        supplierId: [
          { required: true, message: '请输入供应商名称ID', trigger: 'blur' }
        ],
        materialId: [
          { required: true, message: '请输入物资名称ID', trigger: 'blur' }
        ],
        quantity: [
          { required: true, message: '请输入采购数量', trigger: 'blur' }
        ],
        unitPrice: [
          { required: true, message: '请输入单价', trigger: 'blur' }
        ],
        orderStatus: [
          { required: true, message: '请选择订单状态', trigger: 'change' }
        ]
      },
      selectedRows: [],
      statusOptions: {
        1: '新建',
        2: '已确认',
        3: '已完成'
      }
    }
  },
  methods: {
    async handleLoadData() {
      try {
        const response = await request.get('/purchase-orders/page', {
          params: {
            current: this.currentPage,
            size: this.pageSize,
            ...this.searchForm
          }
        })
        
        this.tableData = response.records;
        this.total = response.total;
      } catch (error) {
        console.error('获取采购订单数据失败:', error)
        this.$message.error('获取采购订单数据失败')
        this.tableData = []
        this.total = 0
      }
    },

    handleSearch: _.debounce(async function () {
      this.currentPage = 1
      await this.handleLoadData()
    }, 300),

    async resetSearch() {
      this.searchForm = {
        orderId: '',
        supplierId: '',
        materialId: '',
        orderStatus: ''
      }
      this.currentPage = 1
      await this.handleLoadData()
    },

    handleAdd() {
      this.dialogTitle = '新增采购订单'
      this.purchaseOrderForm = {
        supplierId: '',
        materialId: '',
        quantity: 1,
        unitPrice: 0,
        totalAmount: 0,
        orderStatus: 1
      }
      this.dialogVisible = true
    },

    handleEdit(row) {
      this.dialogTitle = '编辑采购订单'
      this.purchaseOrderForm = {
        ...row,
        orderId: row.orderId
      }
      this.dialogVisible = true
    },

    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该采购订单吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        await request.delete(`/purchase-orders/${row.orderId}`)

        this.$message.success('删除成功')
        await this.handleLoadData()
      } catch (error) {
        if (error === 'cancel') {
          this.$message.info('已取消删除')
        } else {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }
    },

    async handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      await this.handleLoadData()
    },

    async handleCurrentChange(val) {
      this.currentPage = val
      await this.handleLoadData()
    },

    // 新增选择行的方法
    handleSelectionChange(val) {
      this.selectedRows = val
    },

    // 新增批量删除的方法
    async handleBatchDelete() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请选择要删除的订单')
        return
      }

      try {
        await this.$confirm('确认删除选中的订单吗？', '提示', {
          type: 'warning'
        })

        const orderIds = this.selectedRows.map(row => row.orderId)
        await request.delete('/purchase-orders/batch', {
          data: orderIds
        })

        this.$message.success('批量删除成功')
        await this.handleLoadData()
      } catch (error) {
        if (error === 'cancel') {
          this.$message.info('已取消删除')
        } else {
          console.error('批量删除失败:', error)
          this.$message.error('批量删除失败')
        }
      }
    },

    async submitForm() {
      try {
        const valid = await this.$refs.purchaseOrderForm.validate()
        if (!valid) return

        const formData = {
          ...this.purchaseOrderForm
        }
        
        // 计算总金额
        formData.totalAmount = formData.quantity * formData.unitPrice

        if (this.purchaseOrderForm.orderId) {
          await request.put('/purchase-orders', formData)
        } else {
          await request.post('/purchase-orders', formData)
        }

        this.$message.success(this.purchaseOrderForm.orderId ? '更新成功' : '添加成功')
        this.dialogVisible = false
        await this.handleLoadData()
      } catch (error) {
        console.error('保存失败:', error)
        this.$message.error('保存失败，请稍后重试')
      }
    },

    // 新增获取状态文本的方法
    getStatusText(status) {
      const statusMap = {
        1: '新建',
        2: '已确认',
        3: '已完成'
      }
      return statusMap[status] || '未知状态'
    },

    // 新增获取状态标签类型的方法
    getStatusType(status) {
      const typeMap = {
        1: 'primary',    // 新建 - 蓝色
        2: 'warning',    // 已确认 - 黄色
        3: 'success'     // 已完成 - 绿色
      }
      return typeMap[status] || ''
    },

    // 获取供应商名称列表
    async fetchSuppliers() {
      try {
        const response = await request.get('/supplier/supplierAll')
        this.supplierOptions = response
      } catch (error) {
        console.error('获取供应商名称列表失败:', error)
        this.$message.error('获取供应商名称列表失败')
      }
    },

    // 获取物资名称列表
    async fetchMaterials() {
      try {
        const response = await request.get('/material/materialAll')
        this.materialOptions = response
      } catch (error) {
        console.error('获取物资名称列表失败:', error)
        this.$message.error('获取物资名称列表失败')
      }
    },

    // 根据ID获取供应商名称名称
    getSupplierName(id) {
      const supplier = this.supplierOptions.find(item => item.supplierId === id)
      return supplier ? supplier.supplierName : '未知供应商'
    },

    // 根据ID获取物资名称名称
    getMaterialName(id) {
      const material = this.materialOptions.find(item => item.materialId === id)
      return material ? material.materialName : '未知物资'
    }
  },
  created() {
    this.handleLoadData()
    this.fetchSuppliers()
    this.fetchMaterials()
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.operation-bar {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.el-button {
  margin-left: 10px;
}

.el-table {
  margin-top: 20px;
}

.el-table th,
.el-table td {
  padding: 12px 0;
}

.el-table th {
  background-color: #f5f7fa;
  color: #909399;
}

.el-table .el-button {
  padding: 7px 15px;
  font-size: 12px;
}

.el-table .el-button + .el-button {
  margin-left: 5px;
}

.form-row {
  display: flex;
  gap: 20px;

  .el-form-item {
    flex: 1;
    margin-bottom: 18px;
  }
}

.el-tag {
  display: inline-block;
  height: 27px;
  padding: 0 10px;
  line-height: 30px;
  font-size: 12px;
  border-width: 1px;
  border-style: solid;
  border-radius: 4px;
  box-sizing: border-box;
  white-space: nowrap;

  &--primary {
    background-color: #ecf5ff;
    border-color: #d9ecff;
    color: #409EFF;
  }

  &--warning {
    background-color: #fdf6ec;
    border-color: #faecd8;
    color: #e6a23c;
  }

  &--success {
    background-color: #f0f9eb;
    border-color: #e1f3d8;
    color: #67c23a;
  }
}
</style>